#include "uli.hpp" 




//多线程客户端，一个线程用于用户IO，一个线程用于接收广播消息

struct sockaddr_in server;  //服务器信息
volatile bool quit=false;

static void Usage(std::string name){
    std::cout << "Usage:\n\t" << name << " server_ip server_port" << std::endl;
}


void* recv_rounite(void* arg){
    while (true)
    {
        int sockfd=*(int*)arg;
        char buff[1024];
        struct sockaddr_in client;
        socklen_t len=sizeof(client);
        ssize_t s=read(sockfd,buff, sizeof(buff) - 1);
        if (s > 0)
        {
            buff[s] = 0;
            std::cout << "server echo# " << buff << std::endl;
        }
    }
    
}
int main(int argc,char*argv[]){
    if(argc!=3){
        Usage(argv[0]);
        exit(1);
    }

    std::string server_ip=argv[1];
    uint16_t server_port=atoi(argv[2]);  

    int sockfd=socket(AF_INET,SOCK_STREAM,0);
    if (sockfd< 0)
    {
        std::cerr << "socket: " << strerror(errno) << std::endl;
        exit(SOCKET_ERR);
    }
    bzero(&server,sizeof(server));
    server.sin_family=AF_INET;
    server.sin_port=htons(server_port);
    server.sin_addr.s_addr=inet_addr(server_ip.c_str());
    socklen_t len=sizeof(server);
    int ret=connect(sockfd,(const sockaddr*)&server,len);
    //接收消息
    pthread_t rev;
    pthread_create(&rev,nullptr,recv_rounite,(void*)&sockfd);

    string buffer;
    //用户进行IO操作
    while(true){
        std::cerr<<"please Enter#  ";
        std::getline(std::cin,buffer);
        //判断用户是否需要退出
        if(strcasecmp(buffer.c_str(),"quit")==0){
            quit=true;
            break;
        }
        ssize_t s=write(sockfd,buffer.c_str(),sizeof(buffer.c_str())-1);
        if(s>0){
            continue;
        }
        else if(s<=0){
            break;
        }
    }
    close(sockfd);

    return 0;
}

